package com.wms.ymcc.userdetails;

import com.wms.ymcc.domain.Login;
import com.wms.ymcc.domain.Permission;
import com.wms.ymcc.exception.GlobalBaseException;
import com.wms.ymcc.service.ILoginService;
import com.wms.ymcc.service.IPermissionService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

         // 根据用户名查询登陆信息
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username",username);
        Login login = loginService.selectOne(wrapper);

        if(login==null){
            throw new GlobalBaseException("用户不存在");
        }

        // 根据用户查询对应权限表,没有校验
        List<Permission> permissions = permissionService.selectPermissionByLoginId(login.getId());

        // 存入当前用户对应的权限信息的
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        for (Permission permission : permissions) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getSn());
            authorities.add(simpleGrantedAuthority);
        }

        // TODO   插眼：把  List<Permission> permissions  ====》 authorities

        // 把loginId封装到user对象中
        // 自己准备一个login对象，就是为了封装数据
        Login login1 = new Login();
        login1.setId(login.getId());
        login1.setUsername(login.getUsername());
        login1.setAvatar(login.getAvatar());

        // 把login1对象，转成json字符串
        String jsonString = JSONObject.toJSONString(login1);

        User user = new User(
                jsonString,
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                authorities);
        return user;
    }
}